#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"
#include <iostream>
#include <functional>
#include <unordered_map>
class translateserver
{
public:
    translateserver(int port)
        : _server(&_eventloop, muduo::net::InetAddress("0,0,0,0", port), "translateserver", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&translateserver::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&translateserver::onMessage,this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void start() // 创建服务器，建立可连接等等
    {
        _server.start();   // 开启监听
        _eventloop.loop(); // 仿reactor模型进行事件监控，非阻塞死循环
    }
    ~translateserver()
    {
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn) // 新连接建立成功后调用的回调函数
    {
        if (conn->connected() == true)
        {
            std::cout << "成功" << std::endl;
        }
        else
        {
            std::cout << "失败" << std::endl;
        }
    }
    std::string translate(std::string &as)
    {
        static std::unordered_map<std::string, std::string> mmap = {
            {"Hello", "你好"},
            {"你好", "Hello"},
            {"World", "世界"},
            {"世界", "World"}
        };
        auto it=mmap.find(as);
        if(it!=mmap.end())
        {
            return it->second;
        }
        return "没听懂!!";
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buff, muduo::Timestamp) // 获取普通请求时调用后调用的回调函数
    {
        //将请求数据全部提取出来转化为字符串
        std::string str=buff->retrieveAllAsString();
        //进行翻译
        std::string re=translate(str);
        //对客户端相应代码
        conn->send(re);
    }

private:
    muduo::net::EventLoop _eventloop; // 事件检测，类似epoll的事件监控，触发事件后进行io操作
    muduo::net::TcpServer _server;    // 底层tcp，这个server主要是用来服务器收到什么请求用什么回调函数答复
};
int main()
{
    translateserver as(8080);
    as.start();
    return 0;
}